import {Component, Fragment} from "react";
import TodoItem from "./TodoItem";
import "./TodoList.css"

class TodoList extends Component {
    constructor(props) {
        super();
        this.state = {
            inputVal: '',
            list: [
                "learn react",
                "learn vue"
            ]
        }
        this.handleInputChange = this.handleInputChange.bind(this)
        this.handleBtnClick = this.handleBtnClick.bind(this)
        this.handleDeleteItem = this.handleDeleteItem.bind(this)
    }

    handleInputChange(e) {
        //没有指定.bind(this)时，this指向为button
        this.setState({
            inputVal: e.target.value
        })
    }

    handleBtnClick() {
        //没有指定.bind(this)时，this指向为button
        this.setState({
            inputVal: "",
            list: [...this.state.list, this.state.inputVal]
        })
    }

    handleDeleteItem(index, e) {
        console.log(index, e)
        //尽量不直接更改原始的list，操作其副本
        const list = [...this.state.list]
        list.splice(index, 1)
        this.setState({list})
    }

    getTodoItems() {
        return (this.state.list.map((item, index) => {
            return (
                <TodoItem
                    key={index}
                    content={item}
                    index={index}
                    delete={this.handleDeleteItem}
                />
            )
        }))
    }

    render() {
        return (
            //React.Fragment 直接将内容放到root标签下（不必在外层包裹div）
            <Fragment>
                <div>
                    <input value={this.state.inputVal} onChange={this.handleInputChange}/>
                    <button className='red-btn' onClick={this.handleBtnClick}>add</button>
                </div>
                <ul>{this.getTodoItems()}</ul>
            </Fragment>
        );
    }
}

export default TodoList;
